<template>
  <div class="goodsStockUpload">
    <el-row
      type="flex"
      justify="center"
    >
      <el-button
        type="primary"
        @click="downLoadTmp"
      >下载导入模板</el-button>
    </el-row>
    <el-row
      type="flex"
      justify="center"
      class="content"
    >
      <el-upload
        class="upload-demo"
        :show-file-list="false"
        drag
        action="https://jsonplaceholder.typicode.com/posts/"
        :on-success="onSuccess"
        :http-request="httpRequest"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
    </el-row>
    <el-row
      type="flex"
      justify="center"
    >
      <el-button @click="$emit('update:centerDialogVisible', false)">取 消</el-button>
      <!-- <el-button type="primary">确 定</el-button> -->
    </el-row>

  </div>
</template>

<script>
import XLSX from 'xlsx'
import { getGoodsList, updateGoodsList } from '@/api/goods'
import { addIncomePay } from '@/api/incomePay'
export default {
  props: {
    centerDialogVisible: {
      type: Boolean
    }
  },
  data () {
    return {
      indexS: 0
    }
  },
  methods: {
    /* 
      导入成功
    */
    onSuccess () {
      if (this.indexS == 0) {
        this.$message({
          message: '修改商品库存成功',
          type: 'success'
        })
        this.$emit('success')
      }
      this.indexS++
    },
    /* 
      下载模板
    */
    downLoadTmp () {
      const headers = {
        "商品ID": "id",
        "商品名称": "goodsName",
        "商品价格(元)": "goodsPrice",
        "库存（个）": "goodsStock",
        "商品类型": "goodsType",
        "商品描述": "goodsContent"
      }
      import('@/utils/Export2Excel').then(async excel => {
        const rst = await getGoodsList('?')
        rst.forEach(item => {
          item.id = item.id.toString()
        })
        const data = this.formatJson(headers, rst)
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '库存导入模板',
          autoWidth: true,
          bookType: 'xlsx',
        })
      })

    },
    /* 
      导出的辅助函数
    */
    formatJson (headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === "type") {
            // console.log(item[headers[key]]);
            return Rooms.type.find(obj => obj.id === item[headers[key]]).value
          } else if (headers[key] === "state") {
            // console.log(item[headers[key]]);
            return Rooms.state.find(obj => obj.id === item[headers[key]]).value
          } else {
            return item[headers[key]]
          }
        })
      })
    },
    /* 
      上传函数
    */
    readerData (rawFile) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = e => {
          const data = e.target.result
          // 这里使用 XLSX 
          const workbook = XLSX.read(data, { type: 'array' })
          // 这里 firstSheetName 是获取 sheet 页  [0] 获取的是第一页 想要获取全部需要循环处理
          const firstSheetName = workbook.SheetNames[0]
          // 获取 sheet 页里面的数据 
          const worksheet = workbook.Sheets[firstSheetName]
          // 获取到表头
          const header = getHeaderRow(worksheet)
          // 获取表体
          const results = XLSX.utils.sheet_to_json(worksheet)
          resolve({ header, results })
        }
        reader.readAsArrayBuffer(rawFile)
      })
    },
    /* 
      覆盖默认上传函数
    */
    httpRequest (params) {
      let that = this;
      //拿到所导入文件的名字
      let fileName = params.file
      //定义reader，存放文件读取方法
      let reader = new FileReader()
      //启动函数
      reader.readAsBinaryString(fileName)
      //onload在文件被读取时自动触发
      reader.onload = async function (e) {
        this.indexS = 0
        let uploadData = [];
        //workbook存放excel的所有基本信息
        const workbook = XLSX.read(e.target.result, { type: 'binary' });
        //定义sheetList中存放excel表格的sheet表，就是最下方的tab
        let worksheet1 = workbook.SheetNames[0]// 工作表名称集合
        const worksheet = workbook.Sheets[worksheet1]
        // 获取到表头
        const header = getHeaderRow(worksheet)
        // 获取表体
        const results = XLSX.utils.sheet_to_json(worksheet)
        const data = []
        results.forEach(item => {
          data.push({
            id: item['商品ID'],
            goodsName: item['商品名称'],
            goodsPrice: item['商品价格(元)'],
            goodsStock: item['库存（个）'],
            goodsType: item['商品类型'],
            goodsContent: item['商品描述']
          })
        })
        const resultData = await getGoodsList('?')
        await resultData.forEach(async item => {
          await data.forEach(async items => {
            if (item.id == items.id && items.goodsStock != item.goodsStock) {
              // 记录订单
              if (items.goodsStock > item.goodsStock) {
                await addIncomePay({
                  payment: (items.goodsStock - item.goodsStock) * items.goodsPrice,
                  info: `增加了${items.goodsName}的商品库存`
                })
              } else if (items.goodsStock < item.goodsStock) {
                await addIncomePay({
                  income: (item.goodsStock - items.goodsStock) * items.goodsPrice,
                  info: `减少了${items.goodsName}的商品库存`
                })
              }
              item.goodsStock = items.goodsStock
              await updateGoodsList(item)
              that.onSuccess()
            }
          })
        })
      };
    }
  }
}
function getHeaderRow (sheet) {
  const headers = []
  const range = XLSX.utils.decode_range(sheet['!ref'])
  let C
  const R = range.s.r
  /* start in the first row */
  for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
    const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
    /* find the cell in the first row */
    let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
    if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
    headers.push(hdr)
  }
  return headers
}
</script>

<style scoped>
.content {
  padding: 50px;
}
</style>
